﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Data;
using CPPEI.Coolzon.Metadata;
using CPPEI.Coolzon.Server.CacheData;
using CPPEI.Coolzon.Service.Contract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.Server.ServiceImplement
{
    public class ReqGetSolutionListHandler : BaseHandler<ReqGetSolutionListData, RespGetSolutionListData>
    {
        public ReqGetSolutionListHandler()
            : base(Service.Contract.REQUEST_SCENARIO.CONNENT, Service.Contract.REQUEST_COMMAND.CONNECT.GETSOLUTIONLIST)
        {
        }

        protected override RespGetSolutionListData OnHandle(Data.MainServiceData.Request request, ReqGetSolutionListData requestData)
        {
            if (ServerData.IsUpdatingSolution)
            {
                Logger.InfoToTag("MainService", "终端{0}请求获取方案列表,但方案正在更新中,获取失败", request.Header.UserIdentity);
                return null;
            }
            List<SolutionRef> SolutionRefList = SolutionXmlProxy.LoadSolutionList(CZEnvironment.GetSolutionListMetadataFilePath());

            Client client = ServerData.Instance.GetClient(request.Header.UserIdentity);
            if (client != null)
            {
                List<SolutionRef> newSolutionList = new DefaultSolutionFilterStategy().Filter(SolutionRefList, client.AppType);
                if (newSolutionList != null && newSolutionList.Count > 0)
                {
                    RespGetSolutionListData responseData = new RespGetSolutionListData();
                    responseData.Solutions = new SolutionItem[newSolutionList.Count];
                    for (int index = 0; index < newSolutionList.Count; index++)
                    {
                        SolutionRef oSolution = newSolutionList[index];

                        responseData.Solutions[index] = new SolutionItem()
                        {
                            Version = oSolution.Version.ToString(),
                            Caption = oSolution.Caption,
                            Name = oSolution.Name
                        };
                    }

                    return responseData;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }
    }
}
